//
//  RMMTaoCanOrderDetailsViewController.m
//  Romomo
//
//  Created by puman on 2016/12/29.
//  Copyright © 2016年 mazegong. All rights reserved.
//

#import "RMMTaoCanOrderDetailsViewController.h"
#import "RMMTaoCanOrderTimerView.h"
#import "RMMTaoCanPayDetailsTableViewCell.h"
#import "RMMTaoCanConfirmTableViewCell.h"
#import "RMMOrderCommonBottomView.h"
#import "RMMSelcetPickerView.h"
#import "DataSigner.h"
#import "RMMPayJieGuoViewController.h"

@interface RMMTaoCanOrderDetailsViewController ()<UITableViewDelegate, UITableViewDataSource, UIPickerViewDelegate, UIPickerViewDataSource>

@end

@implementation RMMTaoCanOrderDetailsViewController
{
    RMMTaoCanOrderTimerView *_timerView;
    UITableView *_tableView;
    RMMOrderCommonBottomView *_bottomView;
    RMMSelcetPickerView *_pickerView;
    UILabel *_priceLabel;
    NSArray *_array;
    NSInteger _time;
    NSInteger _row;
    BOOL _isSuccess;
    NSString *_pay_way_code;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"订单详情";
    self.view.backgroundColor = kCColor;
    [self addSubViews];
    // Do any additional setup after loading the view.
}
- (void)dealloc{
    NS_REM(@"PAYJIEGUOFUWU", nil);
}
- (void)addSubViews{
    _row = 0;
    _isSuccess = YES;
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    double date = (double)time;
    NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
    NSString *ID = _orderId;
    NSString *key = [NSString stringWithFormat:@"%@%@",cust_id,ID];
    NSString *saveTime = [[RMMFileManager shareHandle] getValeForKey:key];
    if (!saveTime.length) {
        saveTime = [NSString stringWithFormat:@"%f",30 * 60 + date];
        [[RMMFileManager shareHandle] saveVale:[NSString stringWithFormat:@"%f",30 * 60 + date] forKey:key];
    }
    [[RMMFileManager shareHandle].userDefaults removeObjectForKey:key];
    _timerView = [[RMMTaoCanOrderTimerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 38)];
    [self.view addSubview:_timerView];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, _timerView.bottom, kScreenWideth, kScreenHeight - 49 - 38 - 64) style:(UITableViewStylePlain)];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 0)];
    [_tableView registerClass:[RMMTaoCanConfirmTableViewCell class] forCellReuseIdentifier:@"ACell"];
    [_tableView registerClass:[RMMTaoCanPayDetailsTableViewCell class] forCellReuseIdentifier:@"PCell"];
    [self.view addSubview:_tableView];
    
    _bottomView = [[RMMOrderCommonBottomView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 64 - 49, kScreenWideth, 49)];
    _bottomView.type = @"去支付";
    BUTTON_S(_bottomView.leftButton, leftButtonClick);
    BUTTON_S(_bottomView.but, butClick);
    [self.view addSubview:_bottomView];
    
    _array = @[@"忘记用优惠券喽",@"突然有事很不好意思",@"重新选定项目",@"需要换个美容师",@"手一哆嗦多拍了"];
    _pickerView = [[RMMSelcetPickerView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, kScreenHeight - 64)];
    _pickerView.pickerView.delegate = self;
    _pickerView.pickerView.dataSource = self;
    BUTTON_S(_pickerView.rihthBut, doneButClick);
    _pickerView.type = @"location";
    _pickerView.hidden = YES;
    [self.view addSubview:_pickerView];

}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSArray *array = _dic[@"PROD_SERVICES"];
        return 70 + 20 * array.count;
;
    } else {
        return 220;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 44)];
        view.backgroundColor = kWhiteColor;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, view.width - 30, view.height)];
        label.text = @"商品详情";
        label.textColor = COLORFROMCODE(0x4A4A4A, 1);
        label.font = kFont(13);
        [view addSubview:label];
        return view;
    } else {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWideth, 44)];
        view.backgroundColor = kCColor;
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, view.height)];
        label.backgroundColor = kWhiteColor;
        label.text = @"    订单金额:";
        label.textColor = COLORFROMCODE(0x9B9B9B, 1);
        label.font = kFont(13);
        [view addSubview:label];

        _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(label.right, 0, view.width - label.right - 15, view.height)];
        _priceLabel.textAlignment = NSTextAlignmentRight;
        _priceLabel.textColor = COLORFROMCODE(0x000000, 1);
        _priceLabel.backgroundColor = kWhiteColor;
        _priceLabel.font = kFont(13);
        _priceLabel.text = [NSString stringWithFormat:@"¥%@",_totalPrice];
        [view addSubview:_priceLabel];

        return view;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 44;
    } else {
        return 54;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        RMMTaoCanConfirmTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ACell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.payDic = _dic;
        return cell;

    } else {
        RMMTaoCanPayDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PCell"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.dic = _orderDic;
        return cell;
    }
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return _array.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    return _array[row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    _row = row;
}
- (void)butClick{
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    parDic[@"order_no"] = _orderDic[@"ORDER_NO"];
    parDic[@"atm"] = @"0.01";
    NSString *url = GetALiPaySignUrl;
    [OSRequestManager requestWithUrlString:url parDic:parDic method:GET finish:^(NSDictionary *dataDic) {
        NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
        if ([status isEqualToString:@"1"]) {
            NS_ADD(payJieGuo:, @"PAYJIEGUOFUWU", @"套餐购买");
            [self aLipayWith:[self backStringWithDic:dataDic[@"data"]]];
        } else {
            [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
        }
    } error:^(NSError *errors) {
        
    } view:self.view];
}
- (void)payJieGuo:(NSNotification *)notification{
    if ([notification.object isEqualToString:@"套餐购买"]) {
        NSDictionary *dic = [notification userInfo];
        NSString *status = dic[@"resultStatus"];
        if ([status isEqualToString:@"9000"]) {
            // 支付成功
            if (_isSuccess) {
                _isSuccess = NO;
                NSString *cust_id = [RMMFileManager retrunObjWith:[RMMFileManager shareHandle].userDic[@"CUST_ID"]];
                NSString *ID = _orderId;
                NSString *key = [NSString stringWithFormat:@"%@%@",cust_id,ID];
                [RMMFileManager removeObjForKey:key];
                RMMPayJieGuoViewController *VC = [[RMMPayJieGuoViewController alloc] init];
                VC.nameTitle = @"测试套餐";
                VC.balance = @"0.01";
                [self.navigationController pushViewController:VC animated:YES];
            }
        } else {
            [RMMFileManager MBProgressWith:dic[@"memo"] onView:self.view];
        }
    }
}
- (void)aLipayWith:(NSString *)sign{
        [[AlipaySDK defaultService] payOrder:sign fromScheme:ALiPaySchemes callback:^(NSDictionary *resultDic) {
            // 如果支付成功后
            NSLog(@"reslut = %@",resultDic);
        }];
}
// 取消订单
- (void)leftButtonClick{
    _pickerView.hidden = NO;
    [UIView animateWithDuration:kInterval animations:^{
        _pickerView.view.frame = CGRectMake(0, kScreenHeight - 64 - 249, kScreenWideth, 249);
        _pickerView.backView.alpha = 1.0;
    } completion:^(BOOL finished) {
    }];

}
- (void)doneButClick{
    [UIView animateWithDuration:kInterval animations:^{
        _pickerView.view.frame = CGRectMake(0, kScreenHeight - 64, kScreenWideth, 249);
        _pickerView.backView.alpha = 0.0;
    } completion:^(BOOL finished) {
        _pickerView.hidden = YES;
        // 取消订单
        NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
        parDic[@"order_id"] = _orderId;
        parDic[@"cancelremak"] = _array[_row];
        NSString *url = CancelOrderUrl;
        [OSRequestManager requestWithUrlString:url parDic:parDic method:POST finish:^(NSDictionary *dataDic) {
            NSString *status = [NSString stringWithFormat:@"%@",dataDic[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [MMProgressHUD show];
                [MMProgressHUD dismissWithSuccess:@"取消订单成功!" title:nil afterDelay:1.0];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.navigationController popToRootViewControllerAnimated:YES];
                });
            } else {
                [RMMFileManager MBProgressWith:dataDic[@"message"] onView:self.view];
            }
        } error:^(NSError *errors) {
            
        } view:self.view];
    }];

}
- (NSString *)backStringWithDic:(NSDictionary *)dic{
    NSMutableArray *arr = [NSMutableArray array];
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *string = [NSString stringWithFormat:@"%@=%@",(NSString *)key,(NSString *)obj];
        [arr addObject:string];
    }];
    NSString *str = [arr componentsJoinedByString:@"&"];
    return str;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
